using UnityEngine;

using System.Collections;

public class TransDoor : MonoBehaviour
{
    //private Camera cam;

    public Shader transDoorShader;
    private Material transDoorMat = null;
    public Material material{
        get {
            transDoorMat = CheckShaderAndCreateMaterial(transDoorShader, transDoorMat);
            return transDoorMat;
        }
    }

    [Range(0,10)]
    public int iterations = 3;

    [Range(1, 8)]
    public int downSample = 2;

    [Range(0, 1)]
    public float focus = 0.2f;

    [Range(0, 100)]
    public float nearScale = 50.0f;

    [Range(0, 100)]
    public float farScale = 20.0f;

    protected void Start() {
		//CheckResources();
        //cam = this.GetComponent<Camera>();
        //cam.depthTextureMode |= cam.depthTextureMode;
	}

    void OnRenderImage (RenderTexture src, RenderTexture dest) {
        if (material != null) {

            int rtW = src.width/downSample;
            int rtH = src.height/downSample;

            RenderTexture buffer0 = RenderTexture.GetTemporary(rtW, rtH, 0);
            RenderTexture buffer1 = RenderTexture.GetTemporary(rtW, rtH, 0);

            //Graphics.Blit(src, buffer0);

            Graphics.Blit(src, dest, material, 0);

            
            // material.SetTexture("_Dof", buffer0);
            // material.SetFloat("_Focus", focus);
            // material.SetFloat("_NearScale", nearScale);
            // material.SetFloat("_FarScale", farScale);

            // Graphics.Blit(src, dest, material, 1);

            //Graphics.Blit(buffer0, dest);

            RenderTexture.ReleaseTemporary(buffer0);
        }
        else{
            Graphics.Blit(src, dest);
        }
    }

    protected Material CheckShaderAndCreateMaterial(Shader shader, Material material) {
		if (shader == null) {
			return null;
		}
		
		if (shader.isSupported && material && material.shader == shader)
			return material;
		
		if (!shader.isSupported) {
			return null;
		}
		else {
			material = new Material(shader);
			material.hideFlags = HideFlags.DontSave;
			if (material)
				return material;
			else 
				return null;
		}
	}

}
